package com.dingdang.sms.allinone.sender.impl

import com.dingdang.sms.allinone.config.AllInOneConfigurationProperties
import com.dingdang.sms.allinone.sender.AllInOneSender
import com.dingdang.sms.allinone.sender.ResultWrapper
import com.dingdang.sms.allinone.sender.Target
import com.github.qcloudsms.SmsMultiSender
import com.github.qcloudsms.SmsSingleSender

class TencentCloudSender(private val properties: AllInOneConfigurationProperties) : AllInOneSender {

    override fun send(target: Target, block: (ResultWrapper) -> Unit) {
        val result = send(target)
        block(result)
    }

    override fun send(target: Target): ResultWrapper {
        if (properties.tencentCloud == null) {
            return ResultWrapper().error("未找到腾讯云短信相关配置")
        }
        if (properties.tencentCloud!!.appId == null) {
            return ResultWrapper().error("未找到腾讯云短信相关配置")
        }
        if (properties.tencentCloud!!.appKey.isNullOrEmpty()) {
            return ResultWrapper().error("未找到腾讯云短信相关配置")
        }

        return if (target.isSingleTarget()) {
            sendSingle(target)
        } else {
            sendMulti(target)
        }
    }

    private fun sendSingle(target: Target): ResultWrapper {
        val sender = SmsSingleSender(
            properties.tencentCloud!!.appId!!,
            properties.tencentCloud!!.appKey!!
        )
        val params = target.params
        val response = sender.sendWithParam(
            target.nationCode,
            target.mobileList!!.first(),
            target.templateId!!.toInt(),
            params?.values?.toTypedArray(),
            properties.tencentCloud!!.signName,
            null,
            null
        )
        return if (response.result == 0) {
            ResultWrapper().ok(message = response.errMsg)
        } else {
            ResultWrapper().error(status = response.result, message = response.errMsg)
        }
    }

    private fun sendMulti(target: Target): ResultWrapper {
        val sender = SmsMultiSender(
            properties.tencentCloud!!.appId!!,
            properties.tencentCloud!!.appKey!!
        )
        val params = target.params
        val response = sender.sendWithParam(
            target.nationCode,
            target.mobileList!!.toTypedArray(),
            target.templateId!!.toInt(),
            params?.values?.toTypedArray(),
            properties.tencentCloud!!.signName,
            null,
            null
        )
        return if (response.result == 0) {
            ResultWrapper().ok(message = response.errMsg, data = response.details)
        } else {
            ResultWrapper().error(status = response.result, message = response.errMsg, data = response.details)
        }
    }

}
